<?php 
namespace app\adm\controller;

use think\Db;
class Recharge extends Base
{
	public function index ()
	{
		if (is_post()) {
			$post = input('post.');
			if (input('get.acc') == 'get') {
				return db('recharge')->where('id',input('post.id'))->find();
			}
			if (input('post.id') && (input('get.acc') == 'edit')) {
				$user = db('ns_user')->where('id',$post['uid'])->find();
				$val = [];
				$val['settlemen_funds'] = $user['settlemen_funds']+$post['denom'];
				$val['total_funds'] = $user['total_funds']+$post['denom'];
				$rech = [];
				$rech['congel'] = $post['congel'];
				$rech['con_status'] = 1;
				$rech['status'] = 1;
				$rech['sum'] = $post['denom'];
				Db::startTrans();
				try {
					$last = db('recharge')->where(['con_status'=>1,'uid'=>$post['uid']])->find();
					if ($last) {
						$val['settlemen_funds'] = $val['settlemen_funds']-$last['sum'];
						$val['available_funds'] = $user['available_funds']+$last['sum'];
						$tolast = 0;
						Db::table('recharge')->where('id',$last['id'])->update(['con_status'=>$tolast]);
					}
					Db::table('ns_user')->where('id',$post['uid'])->update($val);
					$rst = Db::table('recharge')->where('id',$post['id'])->update($rech);
					Db::commit();
				} catch (Exception $e) {
					Db::rollback();
				}
				if ($rst) $this->success('充值成功');$this->error('充值失败');
			}
		}
		$list = db('recharge')
			-> order('status,con_status desc,rec_time desc')
			-> paginate()
			-> each(function ($item,$key) {
				$item['username'] = db('ns_user')->where('id',$item['uid'])->value('username');
				$item['mobile'] = db('ns_user')->where('id',$item['uid'])->value('mobile');
				return $item;
		});
		$this->assign('list', $list);
		return $this->fetch();
	}
}